<template>
<div class="app-container">
  <el-form :inline="true" :model="formData " class="demo-form-inline" >
    <el-form-item label="回货入库单编号">
      <el-input v-model="formData.returnReceiptNo" placeholder="请输入回货入库编号"></el-input>
    </el-form-item>
    <el-form-item label="客户名称">
      <el-input v-model="formData.customerName" placeholder="请输入客户名称"></el-input>
    </el-form-item>
    <el-form-item label="回货申请单编号">
      <el-input v-model="formData.returnApplyNo" placeholder="请输入回货申请单编号"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Search"  >查询</el-button>
      <el-button @click="Reset">重置</el-button>
    </el-form-item>
  </el-form>
  <el-card>
    <el-button  v-hasPermi="['module:returnReceiptOrder:add']" style="margin-bottom: 10px" type="success" icon="el-icon-plus" @click="addOpen">新增</el-button>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="returnReceiptNo" label="回货入库单编号" width="150"></el-table-column>
      <el-table-column
        label="产品信息"
        type="expand"
        width="55">
        <template slot-scope="scope">
          <div style="margin-left:250px; ">
            <el-table :data="scope.row.mechineList" stripe
                      style="width: 70%;">
              <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>
              <el-table-column prop="productNo" label="产品编号" width="120"></el-table-column>
              <el-table-column prop="model" label="型号" width="120"></el-table-column>
              <el-table-column prop="machineNo" label="机器编号" width="120"></el-table-column>
              <el-table-column prop="unit" label="单位" width="120">
                <template slot-scope="scope">
                  <span v-if="scope.row.unit==='1'">台</span>
                </template>
              </el-table-column>
              <el-table-column prop="warehouseName" label="仓库" width="120"></el-table-column>
              <el-table-column prop="remark" label="备注" width="120"></el-table-column>

            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sponsorName" label="发起人" width="120"></el-table-column>
      <el-table-column prop="warehousingTime" label="入库时间" width="120"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
      <el-table-column prop="returnApplyNo" label="回货申请单编号" width="150"></el-table-column>
      <el-table-column prop="salesmanName" label="业务员" width="120"></el-table-column>
      <el-table-column prop="applyWarehouseName" label="申请入库仓库" width="120"></el-table-column>
      <el-table-column prop="warehousingWarehouseName" label="入库仓库" width="120"></el-table-column>
<!--      <el-table-column prop="totalPrice" label="总价" width="120"></el-table-column>-->
      <el-table-column prop="orderStatus" label="订单状态" width="120">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.orderStatus==2">已入库</el-button>
          <el-button type="text" v-if="scope.row.orderStatus==1">待入库</el-button>
        </template>orderStatus
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button v-hasPermi="['module:returnReceiptOrder:remove']" type="text" @click="delFn(scope.row)">删除</el-button>
          <el-button v-hasPermi="['module:returnReceiptOrder:edit']" type="text" size="small" @click="editFn(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="formData.pageNum"
      :page-sizes="[10, 15, 20, 25]"
      :page-size="formData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
<!--  新增弹框-->
  <el-dialog :title="formData.id ? '修改回货入库单' :'添加回货入库单'" :visible.sync="isShow" width="50%" @close="closeDialog">
    <el-form  :model="formData"  ref="form" :rules="rules" inline label-width="120px">
      <el-form-item label="回货申请单编号" prop="returnApplyNo">
        <el-input style="width:250px" v-model="formData.returnApplyNo">
          <template slot="append">
            <el-button style="width:60px" type="primary" @click="returnOrderFn">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
   <el-form-item label="回货入库单号" prop="returnReceiptNo"><el-input v-model="formData.returnReceiptNo"></el-input></el-form-item>
      <el-form-item label="入库时间" prop="warehousingTime"> <el-date-picker
        v-model="formData.warehousingTime"
        type="date"
        placeholder="选择日期">
      </el-date-picker></el-form-item>
      <el-form-item label="发起人" prop="sponsorName"><el-input v-model="formData.sponsorName"></el-input></el-form-item>
  <el-form-item label="客户名称" prop="customerName"><el-input v-model="formData.customerName"></el-input></el-form-item>
  <el-form-item label="业务员" prop="salesmanName"><el-input v-model="formData.salesmanName"></el-input></el-form-item>
  <el-form-item label="申请仓库名称" prop="applyWarehouseName"><el-input v-model="formData.applyWarehouseName"></el-input></el-form-item>
  <el-form-item label="入库仓库" prop="warehousingWarehouseName" ><el-input style="width: 300px;" v-model="formData.warehousingWarehouseName">
    <template slot="append">
      <el-button style="width:60px" type="primary" @click="openImportWarehouse">选择</el-button>
    </template>
  </el-input></el-form-item>
<!--  <el-form-item label="总价" prop="totalPrice"><el-input v-model="formData.totalPrice"></el-input></el-form-item>-->
  <el-form-item label="待入库机器"   >
    <template slot-scope="scope" >
        <el-table :data="stayMachineList"  border style="width: 650px">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column  prop="productName" label="产品名称" width="150"></el-table-column>
          <el-table-column  prop="productNo" label="产品编号" width="150"></el-table-column>
          <el-table-column  prop="model" label="型号" width="150"></el-table-column>
          <el-table-column prop="machineNo" label="机器编号" width="150"></el-table-column>
          <el-table-column prop="status" label="机器状态" width="150">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.status==='0'">正常</el-button>
              <el-button type="text" v-if="scope.row.status==='1'">不可用</el-button>
              <el-button type="text" v-if="scope.row.status==='2'">使用中</el-button>
            </template>
          </el-table-column>
<!--          <el-table-column prop="allPrice" label="售价小计" width="150"></el-table-column>-->
<!--          <el-table-column prop="price" label="退货单价" width="150"></el-table-column>-->
        </el-table>
    </template>
  </el-form-item>

      <el-form-item  label="入库机器编号" prop="machineList">
        <div style="margin-top: 10px">
          <el-input v-model="machineFromData.machineNo" placeholder="请输入机器编码"></el-input>
          <el-button type="success" size="small" @click="searchMachine" >搜索</el-button>
          <el-table :data="formData.mechineList" border style="width: 650px">
            <el-table-column fixed prop="productName" label="产品名称" width="150"></el-table-column>
            <el-table-column prop="productNo" label="产品编号" width="120"></el-table-column>
            <el-table-column prop="model" label="型号" width="120"></el-table-column>
            <el-table-column prop="machineNo" label="机器编号" width="120"></el-table-column>
            <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="delmachine(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="isShow=false">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
    </span>
  </el-dialog>

  <el-dialog
    title="请选择回货申请单"
    :visible.sync="orderListIsShow"
    width="60%"
    @close="OrderListClose">
    <el-form :model="OrderFormData"  inline label-width="100px" >
      <el-form-item label="客户姓名" prop="customerName">
        <el-input style="width:300px" palceholder="请选择客户名称" v-model="OrderFormData.customerName">
          <template slot="append">
            <el-button type="primary" @click="openImportCustomer">
              选择客户
            </el-button>
          </template>>
        </el-input>
      </el-form-item>
<!--      <el-form-item label="订单状态" prop="orderStatus">  <el-select v-model="OrderFormData.orderStatus" placeholder="请选择订单状态">-->
<!--        <el-option-->
<!--          v-for="item in OrderOptions"-->
<!--          :key="item.dictValue"-->
<!--          :label="item.dictLabel"-->
<!--          :value="item.dictValue">-->
<!--        </el-option>-->
<!--      </el-select></el-form-item>-->
      <el-form-item>
        <el-button style=" margin-left: 10px;" size="small" type="success" @click="SearchOrderNo">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="OrderList" tooltip-effect="dark" style="width: 100%">
      <el-table-column label="订单编号" prop="orderNo" width="150"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
      <el-table-column prop="returnApplyNo" label="回库申请编号" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="订单创建时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" show-overflow-tooltip>
        <template slot-scope="scope">

          <el-button type="text" v-if="scope.row.orderStatus==1">已提交</el-button>
          <el-button type="text" v-if="scope.row.orderStatus==2">已入库</el-button>

        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="checked(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <import-warehouse ref="importWarehouse" @showWarehouse="showWarehouse" ></import-warehouse>
  <import-customer ref="importCustomer" @showCustomer="showCustomer"></import-customer>

</div>
</template>
<script>
import {getBackwarehouseList,getBackwarehouseInfoApi,addBackwarehouseApi,editBackwarehouseApi,delBackwarehouseApi,getReturnApplyApi} from '@/api/module/backwarehouses'
import {listOrder} from '@/api/module/order'
import {getBackWarehouseList} from "@/api/module/backapplication";
import {getMachineListApi} from '@/api/module/machine'
import importWarehouse from "@/views/module/product/warehouse";
import {getDicts} from "@/api/system/dict/data";

import importCustomer from "@/views/module/follow/customer";

export default{
  name:"BackWarehouse",
  components:{importWarehouse,importCustomer},

  data(){

    return {
      formData:{
        returnReceiptNo:null,//	是	租赁销售回货入库单号
        warehousingTime:null,//	是	Date	入库时间
        sponsor:null,//	是	Long	发起人
        sponsorName:null,//	是	string	发起人名称
        customerId:null,//	是	Long	客户
        customerName:null,//	是	string	客户名称
        returnApplyId:null,//	是	Long	回货申请单id
        returnApplyNo:null,//	是	string	回货单编号
        salesman:null,//	是	String	业务员
        salesmanName:null,//	是	String	业务员名称
        applyWarehouseId:null,//	是	Long	申请入库仓库
        applyWarehouseName:null,//	是	String	申请入库仓库名称
        warehousingWarehouseId:null,//	是	String	入库仓库
        totalPrice:null,//	是	String	总价
        mechineList:[],//	是	List	回库机器列表

        warehousingWarehouseName:null
      },
      returnQuantity:0,//子申请单待回库数量
      returnApplyProductList:[],//子级回库申请请产品
      total:null,
      rules:{
        returnReceiptNo:[{required:true,message:'请输入回货单号',trigger:'blur'}],
        warehousingTime:[{required:true,message:'请选择入库时间',trigger:'blur'}],

        sponsorName:[{required:true,message:'请输入发起人名称',trigger:'blur'}],
        customerName:[{required:true,message:'请输入客户名称',trigger:'blur'}],
        returnApplyNo:[{required:true,message:'回货单编号',trigger:'blur'}],
        salesmanName:[{required:true,message:'请输入业务员名称',trigger:'blur'}],
        applyWarehouseName:[{required:true,message:'请选择回库仓库',trigger:'blur'}]

      },
      orderListIsShow:false,//控制选择订单编号
      OrderFormData:{
        customerName:'',//客户名称
         customerId:'',
        orderStatus: '1'
      },
      stayMachineList:[],//待入库机器列表
      machineFromData:{
        machineNo:"",
        // productName:null,
        // model:null,
        // warehouseName:null,
      },
      //订单状态
      OrderOptions:[],

      list:[],
      isShow:false,//是否弹框
      //下拉选项数据模拟
      OrderList:[],//订单编号
      value: ''
    }
  },
  created(){
    this.initData()
    this.getRerunStatusOptions()
  },
  methods:{
  //  回货入库单列表
    async initData(){
      let res= await getBackwarehouseList(this.formData)
      console.log(res)
      this.list=res.rows
      this.total=res.total
    },
    handleSizeChange(val) {
      this.formData.pageSize=val
      this.initData()
    },
    handleCurrentChange(val) {
      this.formData.pageNum=val
      this.initData()
    },
    //订单类型
    async getRerunStatusOptions(){
      let res=await getDicts('return_status')
      this.OrderOptions=res.data
    },
    //生成出库订单编号
    setOrderNo(){
      var date = new Date();
      var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
      //修改月份格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      //修改日期格式
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }

      let round = Math.floor(Math.random() * (999 - 100)) + 100;
      var currentFormatDate = `${year}${month}${day}`;
      return "HHRK"+currentFormatDate+round;
    },
    addOpen(){
      this.isShow=true

    },
    //打开仓库
    openImportWarehouse(){
      this.$refs.importWarehouse.show(1);
    },
    showWarehouse(data){
      //仓库
      console.log(data)
      this.formData.warehousingWarehouseId=data.id
      this.formData.warehousingWarehouseName=data.name

    },
    /** 打开客户弹窗 */
    openImportCustomer() {
      this.$refs.importCustomer.show();
    },
    showCustomer(data){
      this.OrderFormData.customerId=data.customerId;
      this.OrderFormData.customerName=data.customerName;
      // this.form.customerCategory=data.category;
      // this.form.customerSource=data.source;
      // this.form.customerRegion=data.region;

    },
    //回库申请单选择按钮
  async  returnOrderFn(){
      let res= await getReturnApplyApi(this.OrderFormData)
      console.log(res)
     this.OrderList=res.rows
     this.orderListIsShow=true

  },
    //查询回库申请单
    async SearchOrderNo(){
      let res= await getReturnApplyApi(this.OrderFormData)
      // console.log(res)
      this.OrderList=res.rows
    },

    //关闭申请单的选择弹框
    OrderListClose(){
      this.OrderFormData={
        customerName: "",
        customerId:'',
        orderStatus:'1'
      }
      this.returnQuantity=0
      this.OrderList=[]
    },
    //选择回库申请单
    async checked(val){
      //查询回库申请单详情
      console.log(val)
      this.returnApplyProductList=val.productList
      let number=0
    val.productList.forEach(item=>{
        number+=Number(item.returnQuantity)


      })
      this.returnQuantity=number
      console.log(this.returnQuantity)
      this.formData.returnApplyNo=val.returnApplyNo
       let res1=await listOrder({orderNo:val.orderNo})
      this.formData.salesman=res1.rows[0].salesman
      this.formData.salesmanName=res1.rows[0].salesmanName

      let res=await getReturnApplyApi({returnApplyNo: val.returnApplyNo,orderId:val.orderId})
      console.log(res)
//   更改属性名

      res.rows[0].machineList.forEach((item, value) => {
          if (item.machine_id) {
            item.machineId = item.machine_id;
            delete item.machine_id;
          }
          if (item.machine_no) {
            item.machineNo = item.machine_no;
            delete item.machine_no;
          }

          if (item.product_id) {
            item.productId = item.product_id;
            delete item.product_id;
          }
          if (item.product_name) {
            item.productName =item.product_name;
            delete item.product_name;
          }
          if (item.product_no) {
            item.productNo = item.product_no;
            delete item.product_no;
          }

          if (item.warehouse_id) {
            item.warehouseId = item.warehouse_id;
            delete item.warehouse_id;
          }
          if (item.warehouse_name) {
            item.warehouseName = item.warehouse_name;
            delete item.warehouse_name;
          }

        });


      console.log(res.rows[0].machineList)

this.stayMachineList=  res.rows[0].machineList
      console.log(this.stayMachineList)
      this.formData.returnReceiptNo=this.setOrderNo()

      this.formData.warehousingTime=res.rows[0].warehousingTime
      this.formData.sponsor=res.rows[0].sponsor
      this.formData.sponsorName=res.rows[0].sponsorName
      this.formData.customerId=res.rows[0].customerId
      this.formData.customerName=res.rows[0].customerName
      this.formData.returnApplyId=res.rows[0].id
      this.formData.returnApplyNo=res.rows[0].returnApplyNo
      // this.formData.salesman=res.rows[0].salesman
      // this.formData.salesmanName=res.rows[0].salesmanName
      this.formData.applyWarehouseId=res.rows[0].warehouseId
      this.formData.applyWarehouseName=res.rows[0].warehouseName
      this.formData.warehousingWarehouseId=res.rows[0].warehousingWarehouseId//入库仓库
      this.formData.totalPrice=res.rows[0].totalPrice
      // this.formData.mechineList=res.rows[0].mechineList

      this.orderListIsShow=false


    },
    //获取机器列表数据

    //搜索机器入库
    async searchMachine(){
      console.log(this.returnQuantity)
   const res=  await getMachineListApi(this.machineFromData)
      console.log(res)
      //111 判断该机器的型号是否和子级申请单型号是否匹配
      let isModel=this.returnApplyProductList.some(item=>{
        return item.model===res.rows[0].model
      })
      console.log(isModel)
        if(!isModel){
          this.$message.warning('该机器型号与申请单型号不匹配')

        }else {
        // 2222判断是否是待回库机器
        let isHave=this.stayMachineList.some( item=>{
          return item.machineNo===res.rows[0].machineNo})
        if(isHave){
          //333 判断是否重复扫码
          let isRepetition=this.formData.mechineList.some(item=>{return item.machineNo===res.rows[0].machineNo})
          if(!isRepetition){
            var machine = res.rows[0];
            this.formData.mechineList.push({
              productName:machine.productName,
              productNo:machine.productNo,
              productId:machine.productId,
              model:machine.model,
              unit:"1",
              machineId:machine.id,
              machineNo:machine.machineNo,
              warehouseId:machine.warehouseId,
              warehouseName:machine.warehouseName,
              remark:''
            })
            this.$message.success('入库成功')} else {this.$message.warning('重复扫码')}

        }else {this.$message.warning('此机器不属于该订单')}
      }


    },
   async editFn(val){
     console.log(val)
      this.isShow=true
      let res=await getBackwarehouseInfoApi(val.id)
     console.log(res)

     this.formData=res.data
         this.productList=val.productList
   },
  //弹框提交
   async btnOk(){
      //  表单验证
      try {
       await this.$refs.form.validate();
        if(this.formData.id){
          await editBackwarehouseApi(this.formData)
        }else{
          await addBackwarehouseApi(this.formData)
        }
        this.$message.success('操作成功')
        this.isShow=false
      } catch (error) {
        console.log(error);
      }


    },
  //查询功能
    Search(){
      this.initData()
},
  //  重置功能
    Reset(){
      this.formData={}
      this.initData()
    },



  // 弹框关闭事件
    async closeDialog(){
      this.formData={
        returnReceiptNo:null,//	是	租赁销售回货入库单号
        warehousingTime:null,//	是	Date	入库时间
        sponsor:null,//	是	Long	发起人
        sponsorName:null,//	是	string	发起人名称
        customerId:null,//	是	Long	客户
        customerName:null,//	是	string	客户名称
        returnApplyId:null,//	是	Long	回货申请单id
        returnApplyNo:null,//	是	string	回货单编号
        salesman:null,//	是	String	业务员
        salesmanName:null,//	是	String	业务员名称
        applyWarehouseId:null,//	是	Long	申请入库仓库
        applyWarehouseName:null,//	是	String	申请入库仓库名称
        warehousingWarehouseId:null,//	是	String	入库仓库
        totalPrice:null,//	是	String	总价
        mechineList:[],//	是	List	回库机器列表

      }
     this.machineFromData={
        machineNo:"",
        // productName:null,
        // model:null,
        // warehouseName:null,
      }

      await this.initData()//表单刷新
    },
  //删除
   async delFn(val){
      await this.$confirm("是否确认删除");
      await delBackwarehouseApi(val.id)
      this.$message.success('删除成功')
      await this.initData()
    },
    //移出机器操作
    delmachine(val){
      this.formData.machineList.splice( val,1)
    }

  }

}
</script>
